const order = require('./order')
const payment = require('./payment')
const time_record = require('./time_record')
const refund = require('./refund')
const complaint = require('./complaint')
const db = require('../../db')  
const { restart } = require('nodemon')
//支付订单
//输入：订单ID，支付密码(string)，支付金额
//需求：生成payment,改变订单状态，生成订单流程记录，从用户账户中扣款(?)
exports.add2paysum = (req,res) =>{
    const userId = req.params.userId;
    const amount = req.params.amonut;
    const q1="UPDATE module3_users SET total_pay = total_pay + ?  WHERE user_id = ? ;"
    const q2="SELECT * FROM module3_users WHERE user_id = ? ;"
    const q3="UPDATE module3_users SET is_VIP = true  WHERE user_id = ? ;"
    let sum=0;
    console.log(q1);
    db.query(q1, [amount,userId], (err, results) => {
        if (err) {
            res.send({
                "status": 1,
                "message": err,
            });
        } else {
            console.log(q2);
            db.query(q2, userId, (err, results) => {
                if (err) {
                    res.send({
                        "status": 1,
                        "message": err,
                    });
                }
                else {
                    sum = results.total_pay;
                    if(sum>=5000) {
                        db.query(q3, userId, (err, results) => {
                            if (err) {
                                res.send({
                                    "status": 1,
                                    "message": err,
                                });
                            } else {
                                res.send({
                                    "status": 0,
                                    "message": "成功添加支付",
                                    "data":sum
                                });
                            }
                        });
                    } else {
                        res.send({
                            "status": 0,
                            "message": "成功添加支付",
                            "data":sum
                        });
                    }
                }
            });
        }
    });
}

exports.pay = (req,res) =>{
    const order_id = req.params.order_id;
    const amount = req.params.amount;
    order.updateOrderState(order_id,1, (err, results) => {
        if (err) {
        console.error(err);
    }
    });
   // console.log('1');
    payment.addNewPayment(order_id,1,amount, (err, results) => {
        if (err) {
        console.error(err);
    }
    });
   // console.log('1');
    time_record.addNewTimeRecord(order_id,1,amount, (err, results) => {
        if (err) {
        console.error(err);
    }
    });
    res.send({
        "status": 0,
        "message": "成功！",
    });
    //待写从用户账户扣款
}

exports.addRefund = (req,res) =>{
    const order_id= req.params.order_id;
    const amount = req.params.amount;
    const refund_reason = req.params.refund_reason;
    refund.addNewRefund(order_id,refund_reason,amount, (err, results) => {
        if (err) {
        console.error(err);
    }
    });
    time_record.addNewTimeRecord(order_id,5, 0,(err, results) => {
        if (err) {
        console.error(err);
    }
});
    order.updateIsRefund(order_id,1, (err, results) => {
        if (err) {
            console.error(err);
        }
    });
    res.send({
        "status": 0,
        "message": "成功！",
    });
}
exports.cancelOrder = (req,res) =>{
 const order_id = req.params.order_id;

    order.updateOrderState(order_id,4, (err, results) => {
        if (err) {
        console.error(err);
    }else if (results.affectedRows !== 1) {
        console.error("更新失败，请稍后再试！");
    }
});

    time_record.addNewTimeRecord(order_id,4, 0,(err, results) => {
        if (err) {
            console.error(err);
        }else if (results.affectedRows !== 1) {
            console.error("更新失败，请稍后再试！");
        }
    });
    res.send({
        "status": 0,
        "message": "成功！",
    });
}
exports.respondComplaint = (req,res) =>{
    const order_id = req.params.order_id;
    const response = req.params.complaint_response;
    complaint.updateComplaintRefonse(order_id,response, (err, results) => {
        if (err) {
        console.error(err);
    }
    });
    time_record.addNewTimeRecord(order_id,8, 0,(err, results) => { 
        if (err) {
        console.error(err);
    }
    });
    order.updateIsComplaint(order_id,2, (err, results) => { 
        if (err) {
        console.error(err);
    }
    });
    res.send({
        "status": 0,
        "message": "成功！",
    });
}
/************************************************************************************************
 * update by sz 2023.6.10
 ***********************************************************************************************/
exports.receive = (req,res) => {
    const order_id = req.params.order_id;
    var flag  = false;
    var old_amount;

    payment.getPaymentAmount(order_id,(err, results)=>{
        if (err) {
            console.error(err);
            flag = true;
        }
        old_amount=results;
        temp_handle();
    });

//     //待写向商家汇款
    if(flag){
        res.send({
            "status": 0,
            "message": "失败！",
        })}

    function temp_handle(){
        order.updateOrderState(order_id,3,(err, results) => {
            var flag = false;
            if (err) {
                console.error(err);
                flag = true;
            }
        });

        payment.updatePaymentState(order_id,2,(err, results) => {
            if (err) {
                console.error(err);
                flag = true;
            }
        });

        payment.updatePaymentAmount(order_id,0,(err, results) => {
            if (err) {
                console.error(err);
                flag = true;

            }
        });

        time_record.addNewTimeRecord(order_id,3,old_amount,(err, results) => {
            if (err) {
                console.error(err);
                flag = true;
            }
        });

        payment.updatePaymentAmount(order_id,0,(err, results) => {
            if (err) {
                console.error(err);
                flag = true;

            }
        });

        res.send({
            "status": 0,
            "message": "成功！",
            "data":old_amount,
        });
    }

}

//输入订单号，查询退款信息
exports.RefundIdSearch = (req, res) => {
    const q = "Select * from module2_refund where order_id = ? ;";
    const values = req.params.order_id;
    db.query(q, values,(err, results) => {
      if (err) return(err.message)
        res.send({
          status: 0,
          message: '数据返回成功！',
          data: results,
        })
    });
};

/*回复退款
输入：订单ID, 退款接受/拒绝(number)，退款理由
需求：修改refund,改变订单状态，生成订单流程记录，修改payment, 汇款至账户余额(?) */
exports.answerRefund= (req,res) =>{
    const order_id=req.params.order_id;
    const flag=req.params.flag;
    const reason=req.params.refund_reason;
    const refund_amount=req.params.amount;

    refund.updateRefundRefuseReason(order_id,reason,flag,(err, results)=>{
        if (err) {
            console.error(err);
        }
    })
    order.updateIsRefund(order_id,2,(err, results)=>{
        if (err) {
            console.error(err);
        }
    })
    if(flag==1){
        time_record.addNewTimeRecord(order_id,6,0,(err, results)=>{
            if (err) {
                console.error(err);
            }
        })
    }else{
        time_record.addNewTimeRecord(order_id,6,refund_amount,(err, results)=>{
            if (err) {
                console.error(err);
            }
        })
        payment.getPaymentAmount(order_id,(err,amount)=>{
            const amount_=amount-refund_amount;
            payment.updatePaymentAmount(order_id,amount_,(err, results)=>{
                if (err) {
                    console.error(err);
                }
            })
            if (err) {
                console.error(err);
            }
        })
    }
    res.send({
        "status": 0,
        "message": "成功！",
    });    
}

/**发起投诉
输入：订单ID, 投诉类型(number)，投诉理由
需求：生成complaint,改变订单状态，生成订单流程记录 */
exports.complain= (req,res) =>{
    const order_id=req.params.order_id;
    const flag=req.params.flag;
    const reason=req.params.complain_reason;
    complaint.addNewComplaint(order_id,reason,flag,(err, results)=>{
        if (err) {
            console.error(err);
        }
    })
    order.updateIsComplaint(order_id,1,(err, results)=>{
        if (err) {
            console.error(err);
        }
    })
    time_record.addNewTimeRecord(order_id,7,0,(err, results)=>{
        if (err) {
            console.error(err);
        }
    })
    res.send({
        "status": 0,
        "message": "成功！",
    });
}

/**发货
输入：订单ID
需求：修改订单状态，生成订单流程记录 */
exports.sendout= (req,res) =>{
    const order_id=req.params.order_id;
    order.updateOrderState(order_id,2,(err, results)=>{
        if (err) {
            console.error(err);
        }
    })
    time_record.addNewTimeRecord(order_id,2,0,(err, results)=>{
        if (err) {
            console.error(err);
        }
    })
    res.send({
        "status": 0,
        "message": "成功！",
    });
}